<template>
    <div class="production-plan">
      <el-button type="success" @click="addjihau" class="save-button">保存主表单和明细</el-button>
      <h3 class="title">质检</h3>
  
      <!-- 基本信息 -->
      <el-form ref="formRef" :model="formData" :rules="rules" label-position="right" label-width="120px"
               class="form-container">
        <el-row :gutter="30">
          <!-- 第一行 -->
          <el-col :span="8">
            <el-form-item label="质检工单主题" style="margin-bottom: 20px;">
              <el-input v-model="formData.qualityWorkOrder" placeholder="请输入质检工单主题" /> <!-- 修改了 placeholder -->
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="质检工单编号" style="margin-bottom: 20px;">
              <el-input v-model="formData.qualityWorkOrderNumber" placeholder="请输入质检工单编号" disabled/> <!-- 修改了 placeholder -->
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="来源工单" style="margin-bottom: 20px;">
              <el-input v-model="formData.sourceWorkOrder" placeholder="请输来源工单"/> <!-- 修改了 placeholder -->
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产物品" style="margin-bottom: 20px;">
              <el-input v-model="formData.generateItems" placeholder="请输生产物品"/> <!-- 修改了 placeholder -->
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="质检负责人" style="margin-bottom: 20px;">
              <el-input v-model="formData.qualityPerson" placeholder="请输入质检负责人" disabled/> <!-- 修改了 placeholder -->
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="质检部门">
              <el-select v-model="formData.qualityDepartment" placeholder="选择质检部门">
                <el-option label="包装部" value="包装部"/>
                <el-option label="生产部" value="生产部"/>
                <el-option label="酵母部" value="酵母部"/>
                <el-option label="原料部" value="原料部"/>
                <el-option label="发酵部" value="发酵部"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工序数量" style="margin-bottom: 20px;">
              <el-input v-model="formData.processQuantity" placeholder="请输入"  />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注信息" style="margin-bottom: 20px;">
              <el-input v-model="formData.remarks" placeholder="请输入" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
  
      <div id="app">
            <el-card>
            <template #header>
                <div class="flex justify-between items-center">
                <span>MinIO 文件上传</span>
                </div>
            </template>
            <el-form ref="formRef1" :model="formData1" label-width="100px">
                <el-form-item label="选择文件">
          <el-upload ref="uploadRef" action="https://localhost:7212/api/FileUpload/UploadFile" :headers="headers"
            :on-success="handleSuccess" :on-error="handleError" :show-file-list="false" :http-request="customRequest">
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
                <el-form-item>
                <el-button type="primary" @click="submitForm">上传文件</el-button>
                </el-form-item>
            </el-form>
            <el-alert v-if="message" :message="message" :type="messageType" :closable="false" style="margin-top: 20px" />
            </el-card>
            <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="key" label="文件名称" width="200" />
            <el-table-column prop="lastModified" label="创建时间" width="200">
                <template #default="scope">
                {{ new Date(scope.row.lastModified).toLocaleString() }}
                </template>
            </el-table-column>
            <el-table-column prop="size" label="文件大小" min-width="200" />
            <el-table-column fixed="right" label="操作" min-width="200">
                <template #default="scope">
                <el-button link type="primary" size="small" @click="openDeleteDialog(scope.row.key)">
                    删除文件
                </el-button>
                <el-button link type="primary" size="small" @click="download(scope.row.key)">下载文件</el-button>
                </template>
            </el-table-column>
            </el-table>
            <el-dialog v-model="isDeleteDialogVisible" title="删除确认" @close="closeDeleteDialog">
            <p>确定要删除该文件吗？</p>
            <template #footer>
                <el-button @click="closeDeleteDialog">取消</el-button>
                <el-button type="primary" @click="confirmDelete">确定</el-button>
            </template>
            </el-dialog>
            <el-dialog v-model="isDownloadDialogVisible" title="文件下载">
            <template #content>
                <el-progress :percentage="downloadProgress" :status="downloadStatus"></el-progress>
            </template>
            <template #footer>
                <el-button @click="closeDownloadDialog">关闭</el-button>
            </template>
            </el-dialog>
        </div>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted, watch } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { useRouter, useRoute } from 'vue-router';
  import { Materialread, Materialwrite } from '@/axios/axiosHelper';
  import axios from 'axios';
  // 未使用到 th，移除该导入
  // import { th } from 'element-plus/es/locales.mjs';
  
  const formRef = ref(null);
  const currentUser = ref("admin");
  const router = useRouter();
  const route = useRoute();
  
  // 主表单数据
  const formData = reactive({
       "qualityid": 0,
        "qualityWorkOrder": "",
        "qualityWorkOrderNumber": "",
        "sourceWorkOrder": "",
        "generateItems": "",
        "qualityPerson": currentUser.value,
        "qualityDepartment": "",
        "processQuantity": '',
        "status": "待质检",
        "remarks": "",
        "isDel": true
  });
  // 主表单验证规则，确保规则中的属性在 formData 中存在
  const rules = reactive({
    qualityWorkOrder: [
      { required: true, message: '不能为空', trigger: 'blur' }
    ],
    qualityDepartment: [
      { required: true, message: '不能为空', trigger: 'blur' }
    ],
   
  });
  
  // 明细数据列表
  const planDetailsList = ref([]);
  const attachments = ref([]);
  
  // 保存主表单
  const addjihau = () => {
    // 表单验证
    formRef.value.validate((valid) => {
      if (valid) {
        Materialwrite.post('f-write/api/Arrival/AddQualityLnspection', formData)
         .then(response => {
            if (response.data.code === 200) {
              ElMessage.success('保存成功');
              console.log(response.data.data);
              router.push("/GetQualityLnspection");
            } else {
              ElMessage.error(`保存失败：${response.data.message}`);
            }
          })
         .catch(error => {
            console.error('保存出错:', error);
            ElMessage.error('保存时出现错误，请检查网络或重试');
          });
      } else {
        ElMessage.error('请填写完整且正确的表单信息');
      }
    });
  };
  
  onMounted(() => {
    // 检查函数是否存在
    
      // fetchAssociatedProjects();
  
   
      fetchAssociatedProjects1();
  
  });
  
  // 对话框显示状态
  const associatedItemDialogVisible1 = ref(false);
  const currentAssociatedItem1 = ref({});
  // 关联项目数据
  const associatedItems1 = ref([]);
  // 打开关联项目选择对话框
  const openAssociatedItemDialog1 = () => {
    associatedItemDialogVisible1.value = true;
  };
  // 当前选中的关联项目行
  const handleAssociatedItemChange1 = (val) => {
    currentAssociatedItem1.value = val;
  };
  // 选择关联项目
  const pickAssociatedItem1 = () => {
    if (currentAssociatedItem1.value) {
      formData.batchNumber = currentAssociatedItem1.value.lotNumber;
  
  
      // 确保 formData 中存在这些属性
      // formData.product_model 不存在于 formData 中，可根据实际情况处理或移除
      // formData.production_batch 不存在于 formData 中，可根据实际情况处理或移除
      // formData.production_date 不存在于 formData 中，可根据实际情况处理或移除
      associatedItemDialogVisible1.value = false;
    }
  };
  // 获取关联项目数据
  const fetchAssociatedProjects1 = () => {
    axios.get("http://localhost:5118/api/MaterialPreparation/Handle")
     .then(res => {
        associatedItems1.value = res.data.data;
      })
  
  };

  const fileList = ref([]);

// 上传前校验
const beforeUpload = (file) => {
  const isLt10M = file.size / 1024 / 1024 < 10;
  const isValidType = ['image/jpeg', 'image/png', 'application/pdf'].includes(file.type);

  if (!isValidType) {
    ElMessage.error('只能上传JPG/PNG/PDF文件!');
    return false;
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!');
    return false;
  }
  return true;
};

// 上传成功
const handleSuccess = (response, file, fileListArr) => {
  if (response.code == 200) {
    ElMessage.success('文件上传成功');
    // 可在此处处理后端返回的文件信息
  } 
  // else {
  //   ElMessage.error('文件上传失败');
  // }
};

// 删除文件
const handleRemove = (file, fileListArr) => {
  // 可在此处处理删除逻辑
};


const formRef1 = ref(null);
const uploadRef = ref(null);
const formData1 = ref({});
const message = ref('');
const messageType = ref('');
const tableData = ref([{
  key: "",
  lastModified: "",
  eTag: "",
  size: 0,
  isDir: false,
  versionId: null,
  contentType: null,
  expires: null,
  userMetadata: null,
  isLatest: false,
  lastModifiedDateTime: "",
}]);
const isDeleteDialogVisible = ref(false);
const currentDeleteKey = ref(''); 
const isDownloadDialogVisible = ref(false);
const downloadProgress = ref(0);
const downloadStatus = ref('');

onMounted(() => {
  listObjects();
});

const download = async (key) => {
  isDownloadDialogVisible.value = true;
  downloadProgress.value = 0;
  downloadStatus.value = 'active';
  try {
    const response = await axios.get(`/api/FileUpload/DownloadFile?objectName=${key}`, {
      responseType: 'blob',
      onDownloadProgress: (progressEvent) => {
        const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        downloadProgress.value = percentCompleted;
      }
    });
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', key);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    downloadStatus.value = 'success';
  } catch (error) {
    console.error('文件下载失败:', error);
    message.value = '文件下载失败: ' + (error.response?.data?.error || error.message);
    messageType.value = 'error';
    downloadStatus.value = 'exception';
  }
};

const listObjects = async () => {
  axios.get("https://localhost:7212/api/FileUpload/ListObjectsInOneBucket")
    .then((res) => {
      tableData.value = res.data;
      console.log("查询成功", res.data);
    })
    .catch((err) => {
      console.log(err);
    });
};

const headers = {
  'Content-Type': 'multipart/form-data'
};

const customRequest = async (options) => {
  const formData = new FormData();
  formData.append('file', options.file);
  const response = await axios.post(options.action, formData, {
    headers: headers
  });
  options.onSuccess(response.data);
  if (response.data != null) {
    alert("添加成功");
    return;
  } else {
    alert("添加失败");
    return;
  }
};

const handleError = (error) => {
  message.value = '上传失败: ' + (error.response?.data?.error || error.message);
  messageType.value = 'error';
};

const submitForm = () => {
  uploadRef.value.submit();
};

const openDeleteDialog = (key) => {
  currentDeleteKey.value = key;
  isDeleteDialogVisible.value = true;
};

const closeDeleteDialog = () => {
  isDeleteDialogVisible.value = false;
  currentDeleteKey.value = '';
};

const confirmDelete = () => {
  axios.delete("https://localhost:7212/api/FileUpload/DeleteObjectInOneBucket", {
    params: {
      objectName: currentDeleteKey.value
    }
  })
    .then((res) => {
      console.log("删除成功", res.data);
      message.value = '文件删除成功';
      messageType.value = 'success';
      listObjects();
      closeDeleteDialog();
    })
    .catch((err) => {
      console.log(err);
      message.value = '文件删除失败: ' + (err.response?.data?.error || err.message);
      messageType.value = 'error';
      closeDeleteDialog();
    });
};

const closeDownloadDialog = () => {
  isDownloadDialogVisible.value = false;
  downloadProgress.value = 0;
  downloadStatus.value = '';
};


  </script>
  
  <style scoped>
  .production-plan {
    padding: 30px;
    background-color: #f0f2f5;
    border-radius: 10px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
    font-family: 'Arial', sans-serif;
  }
  
  .title {
    text-align: center;
    margin-bottom: 30px;
    color: #2c3e50;
    font-size: 24px;
    font-weight: 600;
  }
  
  .save-button {
    display: block;
    margin: 0 auto 30px;
    padding: 12px 24px;
    font-size: 16px;
    border-radius: 6px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
  
  .form-container {
    background-color: white;
    padding: 30px;
    border-radius: 10px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
  }
  
  .el-form-item__label {
    color: #34495e;
    font-size: 16px;
    font-weight: 500;
  }
  
  .el-input,
  .el-input-number,
  .el-date-picker {
    border-radius: 6px;
    border: 1px solid #ccc;
    padding: 10px;
    font-size: 14px;
    transition: border-color 0.3s ease, box-shadow 0.3s ease;
  }
  
  .el-input:focus,
  .el-input-number:focus,
  .el-date-picker:focus {
    border-color: #42b983;
    outline: none;
    box-shadow: 0 0 5px rgba(66, 185, 131, 0.2);
  }
  
  .upload-demo {
  width: 100%;
}
.el-upload__tip {
  color: #909399;
  font-size: 12px;
  margin-top: 7px;
}
  </style>